#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
日志管理器
提供统一的日志记录功能
"""

import logging
import logging.handlers
import sys
from pathlib import Path
from typing import Optional
from config.config_manager import get_config


class LoggerManager:
    """日志管理器"""

    def __init__(self):
        self.config = get_config()
        self._logger = None
        self._setup_logger()

    def _setup_logger(self):
        """设置日志器"""
        # 创建日志器
        self._logger = logging.getLogger('tqsdk_trader')
        self._logger.setLevel(getattr(logging, self.config.logging.level))

        # 清除现有的处理器
        self._logger.handlers.clear()

        # 创建格式器
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )

        # 文件处理器
        if self.config.logging.file_path:
            # 确保日志目录存在
            log_file = Path(self.config.logging.file_path)
            log_file.parent.mkdir(parents=True, exist_ok=True)

            # 创建轮转文件处理器
            file_handler = logging.handlers.RotatingFileHandler(
                filename=self.config.logging.file_path,
                maxBytes=self.config.logging.max_file_size,
                backupCount=self.config.logging.backup_count,
                encoding='utf-8'
            )
            file_handler.setFormatter(formatter)
            self._logger.addHandler(file_handler)

        # 控制台处理器
        if self.config.logging.console_output:
            console_handler = logging.StreamHandler(sys.stdout)
            console_handler.setFormatter(formatter)
            self._logger.addHandler(console_handler)

    def get_logger(self, name: str = None) -> logging.Logger:
        """获取日志器"""
        if name:
            return self._logger.getChild(name)
        return self._logger

    def debug(self, message: str, *args, **kwargs):
        """调试日志"""
        self._logger.debug(message, *args, **kwargs)

    def info(self, message: str, *args, **kwargs):
        """信息日志"""
        self._logger.info(message, *args, **kwargs)

    def warning(self, message: str, *args, **kwargs):
        """警告日志"""
        self._logger.warning(message, *args, **kwargs)

    def error(self, message: str, *args, **kwargs):
        """错误日志"""
        self._logger.error(message, *args, **kwargs)

    def critical(self, message: str, *args, **kwargs):
        """严重错误日志"""
        self._logger.critical(message, *args, **kwargs)

    def exception(self, message: str = "", *args, **kwargs):
        """异常日志"""
        self._logger.exception(message, *args, **kwargs)

    def trade_log(self, symbol: str, action: str, volume: int, price: float = None, order_id: str = None):
        """交易日志"""
        message = f"TRADE - {symbol} - {action} - 手数:{volume}"
        if price is not None:
            message += f" - 价格:{price:.2f}"
        if order_id:
            message += f" - 订单ID:{order_id}"

        self._logger.info(message)

    def position_log(self, symbol: str, position: int, pnl: float = None):
        """持仓日志"""
        message = f"POSITION - {symbol} - 持仓:{position}手"
        if pnl is not None:
            message += f" - 盈亏:{pnl:.2f}"

        self._logger.info(message)

    def risk_log(self, symbol: str, risk_type: str, details: str):
        """风险日志"""
        message = f"RISK - {symbol} - {risk_type} - {details}"
        self._logger.warning(message)

    def performance_log(self, metrics: dict):
        """性能日志"""
        message = "PERFORMANCE - " + " - ".join([f"{k}:{v:.2f}" if isinstance(v, (int, float)) else f"{k}:{v}" for k, v in metrics.items()])
        self._logger.info(message)


# 全局日志管理器实例
_logger_manager = None

def get_logger(name: str = None) -> logging.Logger:
    """获取日志器"""
    global _logger_manager
    if _logger_manager is None:
        _logger_manager = LoggerManager()
    return _logger_manager.get_logger(name)

def init_logger():
    """初始化日志系统"""
    global _logger_manager
    _logger_manager = LoggerManager()
    return _logger_manager

def trade_log(symbol: str, action: str, volume: int, price: float = None, order_id: str = None):
    """交易日志"""
    global _logger_manager
    if _logger_manager:
        _logger_manager.trade_log(symbol, action, volume, price, order_id)

def position_log(symbol: str, position: int, pnl: float = None):
    """持仓日志"""
    global _logger_manager
    if _logger_manager:
        _logger_manager.position_log(symbol, position, pnl)

def risk_log(symbol: str, risk_type: str, details: str):
    """风险日志"""
    global _logger_manager
    if _logger_manager:
        _logger_manager.risk_log(symbol, risk_type, details)

def performance_log(metrics: dict):
    """性能日志"""
    global _logger_manager
    if _logger_manager:
        _logger_manager.performance_log(metrics)
